//
//  NSString+CJKTExtension.m
//  焰火化学
//
//  Created by mac-01 on 2017/4/27.
//  Copyright © 2017年 杭州秀铂科技网络有限公司. All rights reserved.
//

#import "NSString+CJKTExtension.h"

#define EmojiCodeToSymbol(c) ((((0x808080F0 | (c & 0x3F000) >> 4) | (c & 0xFC0) << 10) | (c & 0x1C0000) << 18) | (c & 0x3F) << 24)

@implementation NSString (CJKTExtension)

- (BOOL)judgeEmpty {

    if([self isEqualToString:@""] || self == nil) {
    
        return YES;
        
    }else {
    
        return NO;
        
    }
    
}

+ (NSMutableAttributedString *)replaceEmoji:(NSString *)content toUser:(NSString *)user {
    
    if(!content) {
        
        content = @"未知评论";
        
    }

    NSArray *imgArr = [NSString matchString:content toRegexString:@"<img(.*?)>"];
    
    NSMutableArray *htmlImageArr = [NSMutableArray array];
    
    for (NSString *imgStr in imgArr) {
        NSString *gifPath = [[NSString matchString:imgStr toRegexString:@"src=\".*?\""] firstObject];
        gifPath = [[NSString matchString:gifPath toRegexString:@"\".*?\""] firstObject];
        gifPath = [gifPath stringByReplacingOccurrencesOfString:@"\"" withString:@""];
        
        [htmlImageArr addObject:gifPath];
        
        content = [content stringByReplacingOccurrencesOfString:imgStr withString:gifPath];;
        
    }
    
    NSMutableString *contentStr = [content mutableCopy];
    
    NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithString:content];
    
    for (NSInteger i = htmlImageArr.count - 1; i >= 0; i--) {
        
        NSMutableString *emjStr = [htmlImageArr[i] mutableCopy];
        
        NSRange range = [contentStr rangeOfString:emjStr options:NSBackwardsSearch];
        
        [contentStr deleteCharactersInRange:range];
        
        NSTextAttachment * attachment = [[NSTextAttachment alloc]init];
        attachment.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:emjStr]]];
        attachment.bounds = CGRectMake(0, -3, 15, 15);
        
        NSAttributedString *attachString = [NSAttributedString attributedStringWithAttachment:attachment];

        [string replaceCharactersInRange:range withAttributedString:attachString];
        
        
    }
    
    NSArray *emjArr = [NSString matchString:content toRegexString:@"\\{(.*?)\\}"];
    
    if(emjArr.count != 0) {
        
        for (NSInteger i = emjArr.count - 1; i >= 0; i--) {
            
            NSMutableString *emjStr = [emjArr[i] mutableCopy];
            
            NSRange range = [contentStr rangeOfString:emjStr options:NSBackwardsSearch];
            
            [contentStr deleteCharactersInRange:range];
            
            NSRange deleteRange = [emjStr rangeOfString:@"{"];
            [emjStr deleteCharactersInRange:deleteRange];
            NSRange deleteRange1 = [emjStr rangeOfString:@"}"];
            [emjStr deleteCharactersInRange:deleteRange1];
            NSString *emjOriginStr = [NSString convertHexStrToString:emjStr];
            
            
            
            
            if(emjOriginStr) {
                
                [string replaceCharactersInRange:range withString:emjOriginStr];
                
            }
            
            
            
        }
        
    }
    
    NSArray * registArray = [NSString matchString:content toRegexString:@"\\[.*\\]"];
    
    if (registArray.count !=0) {
        
        for (int i=0; i<registArray.count; i++) {
            
            NSString * imageName = registArray[i];
            
            NSMutableArray *emojArr = [[imageName componentsSeparatedByString:@"]"] mutableCopy];
            
            [emojArr removeLastObject];
            
            NSInteger count = emojArr.count - 1;
            
            for (NSInteger j = count; j >= 0; j--) {
                
                NSString * emojeName = emojArr[j];
                
                NSRange searchRange = [emojeName rangeOfString:@"cjkt-"];
                
                if (searchRange.location != NSNotFound)
                    
                {
                    
                    NSArray * NameArr = [emojeName componentsSeparatedByString:@"cjkt-"];
                    NSString * lastName = [NameArr lastObject];
                    NSArray * lastArr = [lastName componentsSeparatedByString:@"-"];
                    NSString * content = [lastArr firstObject];
                    NSInteger tag = [content integerValue];
                    
                    NSTextAttachment * attachment = [[NSTextAttachment alloc]init];
                    attachment.image = [UIImage imageNamed:[NSString stringWithFormat:@"face%003ld",tag]];
                    attachment.bounds = CGRectMake(0, -3, 15, 15);
                    NSAttributedString *attachString = [NSAttributedString attributedStringWithAttachment:attachment];
                    
                    NSRange range = [contentStr rangeOfString:[NSString stringWithFormat:@"[cjkt-%@-cjkt]",content] options:NSBackwardsSearch];
                    
                    [contentStr deleteCharactersInRange:range];

                    [string replaceCharactersInRange:range withAttributedString:attachString];
                    
                }
                
                
            }
            
            
        }
        
    }
    
    if(![user isEqualToString:@""] && user) {
        
        NSString *nickStr = [NSString stringWithFormat:@"回复 %@：",user];
        
        NSMutableAttributedString *nickAttrStr = [[NSMutableAttributedString alloc] initWithString:nickStr];
        [nickAttrStr addAttributes:@{NSForegroundColorAttributeName:[UIColor orangeColor]} range:[nickStr rangeOfString:[NSString stringWithFormat:@"%@：",user]]];
        [string insertAttributedString:nickAttrStr atIndex:0];
        
    }


    return string;
    
}


//将NSString转换成十六进制的字符串则可使用如下方式:
+ (NSString *)convertStringToHexStr:(NSString *)str {
    if (!str || [str length] == 0) {
        return @"";
    }
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
    
    NSMutableString *string = [[NSMutableString alloc] initWithCapacity:[data length]];
    
    [data enumerateByteRangesUsingBlock:^(const void *bytes, NSRange byteRange, BOOL *stop) {
        unsigned char *dataBytes = (unsigned char*)bytes;
        for (NSInteger i = 0; i < byteRange.length; i++) {
            NSString *hexStr = [NSString stringWithFormat:@"%x", (dataBytes[i]) & 0xff];
    
            if ([hexStr length] == 2) {
                [string appendString:hexStr];
            } else {
                [string appendFormat:@"0%@", hexStr];
            }
        }
    }];
    
    return string;
}

+ (BOOL)isEmojCharacter:(NSString *)substring {
    
    const unichar hs = [substring characterAtIndex:0];
    
    BOOL returnValue = NO;
    
    if (0xd800 <= hs && hs <= 0xdbff) {
        
        if (substring.length > 1) {
            
            const unichar ls = [substring characterAtIndex:1];
            
            const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
            
            if (0x1d000 <= uc && uc <= 0x1f77f) {
                
                returnValue = YES;
                
            }
            
        }
        
    } else if (substring.length > 1) {
        
        const unichar ls = [substring characterAtIndex:1];
        
        if (ls == 0x20e3) {
            
            returnValue = YES;
            
        }
        
    } else {
        
        if (0x2100 <= hs && hs <= 0x27ff) {
            
            returnValue = YES;
            
        } else if (0x2B05 <= hs && hs <= 0x2b07) {
            
            returnValue = YES;
            
        } else if (0x2934 <= hs && hs <= 0x2935) {
            
            returnValue = YES;
            
        } else if (0x3297 <= hs && hs <= 0x3299) {
            
            returnValue = YES;
            
        } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {
            
            returnValue = YES;
            
        }
        
    }
    
    return returnValue;
    
}

//普通字符串转换为十六进制的。
+ (NSString *)hexStringFromString:(NSString *)string{
    NSData *myD = [string dataUsingEncoding:NSUTF8StringEncoding];
    Byte *bytes = (Byte *)[myD bytes];
    //下面是Byte 转换为16进制。
    NSString *hexStr=@"";
    for(int i=0;i<[myD length];i++)
    {
        NSString *newHexStr = [NSString stringWithFormat:@"%x",bytes[i]&0xff];///16进制数
        if([newHexStr length]==1)
            hexStr = [NSString stringWithFormat:@"%@0%@",hexStr,newHexStr];
        else
            hexStr = [NSString stringWithFormat:@"%@%@",hexStr,newHexStr]; 
    } 
    return hexStr; 
}

//将十六进制的字符串转换成NSString则可使用如下方式:
+ (NSString *)convertHexStrToString:(NSString *)str {
    if (!str || [str length] == 0) {
        return nil;
    }
    
    NSMutableData *hexData = [[NSMutableData alloc] initWithCapacity:8];
    NSRange range;
    if ([str length] % 2 == 0) {
        range = NSMakeRange(0, 2);
    } else {
        range = NSMakeRange(0, 1);
    }
    for (NSInteger i = range.location; i < [str length]; i += 2) {
        unsigned int anInt;
        NSString *hexCharStr = [str substringWithRange:range];
        NSScanner *scanner = [[NSScanner alloc] initWithString:hexCharStr];
        
        [scanner scanHexInt:&anInt];
        NSData *entity = [[NSData alloc] initWithBytes:&anInt length:1];
        [hexData appendData:entity];
        
        range.location += range.length;
        range.length = 2;
    }
    NSString *string = [[NSString alloc]initWithData:hexData encoding:NSUTF8StringEncoding];
    return string;
}

+ (NSArray *)matchString:(NSString *)string toRegexString:(NSString *)regexStr
{
    
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexStr options:NSRegularExpressionCaseInsensitive error:nil];
    
    NSArray * matches = [regex matchesInString:string options:0 range:NSMakeRange(0, [string length])];
    
    //match: 所有匹配到的字符,根据() 包含级
    
    NSMutableArray *array = [NSMutableArray array];
    
    for (NSTextCheckingResult *match in matches) {
        
        NSString *component = [string substringWithRange:match.range];
        
        [array addObject:component];
        
        //        for (int i = 0; i < [match numberOfRanges]; i++) {
        //            //以正则中的(),划分成不同的匹配部分
        //            NSString *component = [string substringWithRange:[match rangeAtIndex:i]];
        //
        //            [array addObject:component];
        //
        //        }
        
    }
    
    return array;
}

+ (NSString *)changeAsset:(NSString *)amountStr
{
    if (amountStr && ![amountStr isEqualToString:@""])
    {
        NSInteger num = [amountStr integerValue];
        if (num<=10000)
        {
            return amountStr;
        }
        else
        {
            NSString *str = [NSString stringWithFormat:@"%f",num/10000.0];
            NSRange range = [str rangeOfString:@"."];
            str = [str substringToIndex:range.location+2];
            if ([str hasSuffix:@".0"])
            {
                return [NSString stringWithFormat:@"%@w",[str substringToIndex:str.length-2]];
            }
            else
                return [NSString stringWithFormat:@"%@w",str];
        }
    }
    else
        return @"0";
}

@end
